NL = "\n"

module LastN
  def last(n)
    self[-n,n]
  end
end

class String
  include LastN
end

FOR_REGEX = /(\W*)?for(.\W*)?\(.*\)?/
IF_REGEX = /(\W*)?if(.\W*)?\(/
ELSE_REGEX = /(\W*)?else(.\W*)/
ELSEIF_REGEX = /(\W*)?else.\W*if(.\W*)?\(/
FUNCTION_REGEX = /(\W*)?function(.\W*)?\(.*\)/
STRING_BRACKETS = /(\W*)?String(.\W*)?\[.*\]/
PARENTHESES = /(.\W*)?\(.*\)/
VAR = /(\W*)?var(\W*)?/
NO_SEMICOLON = {"{"=>'',"("=>'',"}"=>'',"+"=>'',";"=>''}


def remove_nils(list)
  new_list = []
  list.each do |line|
    if line != ""
      new_list.push(line)
    end
  end
end

def newline_brackets(code)
  js = code.gsub(/\{/, "{\n")
  h = js.gsub(/\}/, "\n}\n")
  return h
end

def rstrip_newlines(array)
  new_array = []
  new_code = ""
  array.each do |line|
    new_array << line.rstrip
  end
  return new_array
end

def fix_for_loops(code)
  js = code.split("\n")
  new_js = []
  
  i=0  
  while i < js.length do
    if js[i] != ""
      new_js << js[i]
    end
    i+= 1
  end
  js = new_js
  new_js = []
  i = 0
  while i < js.length do
    if js[i].chomp(";")[FOR_REGEX]
      for_loop_construct = js[i].chomp(";").strip + ";"# first part of for..loop
      for_loop_construct += " "+js[i+1].chomp(";").strip + ";"# should be comparison statement
      for_loop_construct += " "+js[i+2].chomp(";").strip # should be comparison statement
      new_js << for_loop_construct
      i+= 3
    elsif js[i] != nil
      #print js[i+incr_lines]
      new_js << add_semicolon(js[i].strip)
      i+=1
    end
  end
  return new_js.join("\n")
end


def process_string_brackets(code)
  js = code.split("\n")
  new_js = []
  i = 0
  end_ = js.length
  while i < end_
    if js[i] != ""
      new_js << js[i]
    end
    i+= 1
  end
  
  js = new_js
  i = 0
  end_ = js.length
  while i < end_
    if js[i][STRING_BRACKETS]
      loc = js[i]
      string = join_additive_strings(loc[STRING_BRACKETS].split("String[")[1].split("]")[0])
      string = loc.sub(STRING_BRACKETS, ' "".'+string)
      js[i] = "// was: "+loc + "\n" + string
    end
    i+= 1
  end
  return js.join("\n")
end

def join_additive_strings(string)
  string = string.split("'+'").join()
  string = string.split('"+"').join()
  string[1,string.length-2]
end

def newline_semicolon(code)
  # split on ';'
  # check for a for construct
  js = code.split(';')
  js = rstrip_newlines(js)
  js = join_semicolons(js).join("\n")
  js = fix_for_loops(js)
  return js
end

def join_semicolons(list_locs)
  code = []
  list_locs.each do |loc|
    code << add_semicolon(loc)
  end
  return code
end

def add_semicolon(line)
   val = line.strip
   if NO_SEMICOLON.has_key?(val[-1,1]) then
     return line
   end
   return line+';'
end

def cleanup_js(code)
  js = newline_brackets(code)
  js = newline_semicolon(js)
  js = process_string_brackets(js)
end
